package com.xuantian.baoming.esyexcelUtil;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xuantian.baoming.BaomingApplication;
import com.xuantian.baoming.entity.OrderInfo;
import com.xuantian.baoming.enums.OrderStatus;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

public class esyexcel {
    /**
     *
     * @param response
     * @param list 导出集合列表
     * @param fileName1 导出文件名 支持中文
     * @param fileName2 导出模板文件名 模板需要放在 resources 下
     */
    private static void excelExprot(HttpServletResponse response, List<T> list, String fileName1,String fileName2){

        String fileName0 = null;
        try {
            fileName0 = URLEncoder.encode( fileName1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
//        UUID uuid = UUID.randomUUID();
        String fileName =fileName0 + System.currentTimeMillis();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename= " + fileName + ".xlsx");

        try (ServletOutputStream outputStream = response.getOutputStream();
             InputStream excelTemplate = BaomingApplication.class.getClassLoader().getResourceAsStream(fileName2)
        ) {

            // 使用 EasyExcel 写入
            EasyExcel.write(outputStream)
                    .withTemplate(excelTemplate)
                    .sheet()
                    .doFill(list);

            // 刷新输出流
            outputStream.flush();

        } catch (IOException e) {
            // 记录异常日志，并在必要时返回错误响应
//            log.error("Error generating Excel file: ", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
//        log.info("========》 excel导出成功,文件名称: {}", fileName);
    }
}
